package com.oguzhan.blog.scheduloor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public final class JobList {

	private List<Job> activeJobList;
	private List<Job> jobHistory;
	private JobTimer timer = new JobTimer();

	public JobList() {
		this.activeJobList = new ArrayList<Job>();
		this.jobHistory = new LinkedList<Job>();
	}

	public void arrange() {
		if (activeJobList.size() > 0) {
			Collections.sort(activeJobList, new JobComparator());
			
			int limit = activeJobList.size() - 1;
			for (int i = 0; i < limit; i++) {
				Job thisJob = activeJobList.get(i);
				switch (thisJob.getStatus()) {
				case CANCELLED:
				case COMPLETED:
				case RUNNING:
					jobHistory.add(thisJob);
					activeJobList.remove(thisJob);
					continue;
				case READY:
					throw new IllegalArgumentException("Job-list cannot have ready state job");
				}
				
				Job nextJob = activeJobList.get(i+1);
				thisJob.setNextJob(nextJob);
				thisJob.cancel();
			}
			
			activeJobList.get(limit).setNextJob(null);
			activeJobList.get(limit).cancel();

			timer.cancel();
			timer = new JobTimer();
			timer.schedule(activeJobList.get(0));
		}
	}

	public boolean add(Job job) {
		if (job != null) {
			job.schedule();
			return activeJobList.add(job);
		}
		else {
			throw new IllegalArgumentException("Cannot add null job to job-list");
		}
	}
	
	public boolean add(Job... jobs) {
		if (jobs != null && jobs.length > 0) {
			for (Job job : jobs) {
				job.schedule();
			}
			
			return activeJobList.addAll(Arrays.asList(jobs));
		}
		else {
			throw new IllegalArgumentException("Cannot add null or empty jobs array to job-list");
		}
	}

	public boolean remove(Job job) {
		if (job != null) {
			job.cancel();
			return activeJobList.remove(job);
		}
		else {
			throw new IllegalArgumentException("Cannot remove null job from job-list");
		}
	}
	
}
